package ddd.ajava.chapter4.question2;
import java.lang.reflect.Field;

public class PersonInput implements PersonAction {
	@Override
	public Person process(Person person) {
		Class<?> clazz = person.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			ValueInput vi = new ValueInput();
			Column column = field.getAnnotation(Column.class);
			boolean flag = true;
			Object value = null;
			while (flag) {
				value = vi.inputValue(column.value(), field.getType()
						.getSimpleName());
				flag=false;
				boolean nullable = column.nullable();
				if (value == null) {
					if (nullable) {
						flag = false;
					} else {
						System.out.println("输入值不能为空，请重新输入。");
					}
				} else {
					int maxlength = column.maxlength();
					int minlength = column.minlength();
					int maxvalue = column.maxvalue();
					int minvalue = column.minvalue();
					if (maxlength != -1) {
						if (((String) value).length() < maxlength) {
							flag = false;
						}else {
							flag = true;
							System.out.println("输入值长度大于最大值，请重新输入。");
							continue;
						}
					}
					if (minlength != -1) {
						if (((String) value).length() > minlength) {
							flag = false;
						}else {
							flag = true;
							System.out.println("输入值长度小于最小值，请重新输入。");
							continue;
						}
					}
					if (maxvalue != -1) {
						if (((Integer)value)  < maxvalue) {
							flag = false;
						}else {
							flag = true;
							System.out.println("输入值大于最大值，请重新输入。");
							continue;
						}
					}
					if (minvalue != -1) {
						if (((Integer)value)  >  minvalue) {
							flag = false;
						}else {
							flag = true;
							System.out.println("输入值小于最小值，请重新输入。");
							continue;
						}
					}
				}
			}
			person = setValue(field, value, person);
		}
		return person;
	}

	private Person setValue(Field field, Object value, Person person) {
		if (field.getName().equals("name")) {
			person.setName((String) value);
		} else if (field.getName().equals("sex")) {
			person.setSex((String) value);
		} else if (field.getName().equals("age")) {
			person.setAge((Integer) value);
		} else if (field.getName().equals("idNo")) {
			person.setIdNo((String) value);
		} else if (field.getName().equals("isMerried")) {
			person.setIsMerried((Boolean) value);
		}
		return person;
	}
}
